package leetcode.offer;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: Offer39_MajorityElement
 * Description: leetcode-剑指offer 39 数组中出现次数超过一半的数字
 * date: 2021-11-18 21:55
 *
 * @author liyifan
 */
public class Offer39_MajorityElement {
    public int majorityElement(int[] nums) {
        int cand = nums[0];
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (count == 0)
                cand = nums[i];
            if (nums[i] == cand)
                count++;
            else
                count--;
        }
        return cand;
    }

    public int majorityElement2(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (Integer x:nums) {
            map.put(x, map.getOrDefault(x, 0) + 1);
        }

        int major = 0;
        int val = 0;
        for (Map.Entry<Integer, Integer> e:
             map.entrySet()) {
            if (e.getValue() > val) {
                val = e.getValue();
                major = e.getKey();
            }
        }
        return major;
    }
}
